
package com.airplane.hotdiscuss.network;

import com.airplane.hotdiscuss.util.Constants;
import com.airplane.hotdiscuss.util.MyLogger;
import com.airplane.hotdiscuss.util.Utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpControllerImpl implements IHttpController, IHttpTaskListener {
    private static final MyLogger logger = MyLogger.getLogger(HttpControllerImpl.class
            .getSimpleName());

    private static IHttpController mInstance;

    private Context mContext;
    private ConnectivityManager mConnManager;
    private MyHttpTask mTask;
    private boolean isUseWifiConn = false;

    private HttpControllerImpl(Context context) {
        mContext = context;
        mConnManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static synchronized IHttpController getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new HttpControllerImpl(context);
        }
        return mInstance;
    }

    @Override
    public MyHttpTask sendRequest(MyHttpRequest request) {
        logger.d("sendRequest() --> Enter");
        mTask = new MyHttpTask(request, this);
        mTask.setTransId(Utils.getTransactionId());
        logger.d("Request type: " + request.getRequestType()
                + ", transId: " + mTask.getTransId());

        if (!isDataLinkOpened()) {
            logger.d("Need to open data link first .");
            if (!openDataLink()) {
                logger.d("Open data link failed !");
            }
        }

        new Thread(mTask).start();

        logger.d("sendRequest() --> Exit");
        return mTask;
    }

    @Override
    public boolean isRunning() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void cancelTaks() {
        if (mTask == null) {
            return;
        }

        mTask.setIsCanceled(true);
    }

    @Override
    public boolean openDataLink() {
        logger.d("Openning data link.");
        if (isWifiConnected()) {
            logger.d("Can use wifi connection.");
            isUseWifiConn = true;
            return true;
        }

        int result = mConnManager.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, Constants.APN_TYPE_WAP);
        logger.d("Open data link result : " + result);
        switch(result) {
            case Constants.APN_ALREADY_ACTIVE:
                return true;
            case Constants.APN_REQUEST_STARTED:
                try {
                    Thread.sleep(3000);
                    logger.d("After sleep 3s, begin to start sevice.");
                } catch (Exception e) {
                    logger.e("The error is:", e.getCause());
                }
            case Constants.APN_REQUEST_FAILED:
                return false;
            case Constants.APN_TYPE_NOT_AVAILABLE:
                logger.d("Not available apn !");
                return false;
            default:
                return false;
        }

    }

    @Override
    public boolean isDataLinkOpened() {
        if (mConnManager == null) {
            logger.d("ConnectivityManager is null !");
            return false;
        }

        NetworkInfo wifiInfo = mConnManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobileInfo = mConnManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        logger.d("wifi state = " + wifiInfo.getState().name() + "; gprs state = "
                + mobileInfo.getState().name());

        if (wifiInfo.isConnected()) {
            return true;
        }
        if (mobileInfo.isConnected()) {
            return true;
        }

        return false;
    }

    @Override
    public boolean isWifiConnected() {
        if (mConnManager == null) {
            return false;
        }
        NetworkInfo wifiInfo = mConnManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifiInfo.isConnected();
    }

    @Override
    public void closeDataLink() {
        if (mConnManager != null || !isUseWifiConn) {
            logger.d("Closing data link.");
            mConnManager.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, Constants.APN_TYPE_DEFAULT);
        }
    }

    @Override
    public void taskCanceled(MyHttpTask task) {
        // TODO Auto-generated method stub

    }

    @Override
    public void taskCompleted(MyHttpTask task) {
        // TODO Auto-generated method stub

    }

    @Override
    public void taskFailed(MyHttpTask task) {
        // TODO Auto-generated method stub

    }

    @Override
    public void taskStarted(MyHttpTask task) {
        // TODO Auto-generated method stub

    }

    @Override
    public void taskTimeOut(MyHttpTask task) {
        // TODO Auto-generated method stub

    }

}
